package com.knife.news.action;

import java.util.ArrayList;
import java.util.List;

import cn.emay.sdk.client.api.Client;

import com.knife.member.Userinfo;
import com.knife.member.UserinfoDAO;
import com.knife.news.logic.SubscribeService;
import com.knife.news.logic.impl.SubscribeServiceImpl;
import com.knife.news.model.Subscribe;
import com.knife.util.CommUtil;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import javax.mail.internet.InternetAddress;
import com.knife.web.ActionContext;
//import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;

import javax.mail.Message;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.Transport;

/*
 * 订阅
 */
public class SubscribeAction extends BaseCmdAction {
	private SubscribeService subscribeDAO = SubscribeServiceImpl.getInstance();

	public Page doInit(WebForm form, Module module) {
		return new Page("ajax", "ajaxResult.txt", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	public Page doList(WebForm form, Module module) {
		List<Subscribe> typeList = subscribeDAO.getAllSubscribes();
		int rows = typeList.size();// 分页开始
		int pageSize = 15;
		int currentPage = 1;
		int frontPage = 1;
		int nextPage = 2;
		int totalPage = (int) Math.ceil((float) (rows) / (float) (pageSize));
		if (nextPage > totalPage) {
			nextPage = totalPage;
		}
		List<Subscribe> firstTypes = subscribeDAO.getSubscribesBySql("id!=''",
				null, 0, pageSize);
		form.addResult("rows", rows);
		form.addResult("pageSize", pageSize);
		form.addResult("frontPage", frontPage);
		form.addResult("currentPage", currentPage);
		form.addResult("nextPage", nextPage);
		form.addResult("totalPage", totalPage);
		form.addResult("subscribeList", firstTypes);
		return module.findPage("list");
	}

	public Page doPage(WebForm form, Module module) {
		List<Subscribe> typeList = subscribeDAO.getAllSubscribes();
		int rows = typeList.size();
		int pageSize = 15;
		int paraPage = CommUtil.null2Int(form.get("page"));
		int frontPage = paraPage - 1;
		int nextPage = paraPage + 1;
		int totalPage = (int) Math.ceil((float) rows / (float) pageSize);
		int begin = (paraPage - 1) * pageSize + 1;
		int end = rows - begin + 1;
		if (frontPage <= 0) {
			form.addResult("msg", "这是第一页了！");
			form.addResult("frontPage", 1);

		} else {
			form.addResult("frontPage", frontPage);
		}
		if (nextPage > totalPage) {
			nextPage = totalPage;
			form.addResult("msg", "这是最后一页了！");
		}
		form.addResult("nextPage", nextPage);
		List<Subscribe> firstTypes = new ArrayList<Subscribe>();
		if (end < pageSize) {
			firstTypes = subscribeDAO.getSubscribesBySql("id!=''", null,
					begin - 1, end);
		} else {
			firstTypes = subscribeDAO.getSubscribesBySql("id!=''", null,
					begin - 1, pageSize);
		}
		form.addResult("currentPage", paraPage);
		form.addResult("totalPage", totalPage);
		form.addResult("rows", rows);
		form.addResult("subscribeList", firstTypes);
		return module.findPage("list");
	}

	// 金客会会员及非会员参与活动短信提示
	public Page doAdd(WebForm form, Module module) {
		Subscribe ss = (Subscribe) form.toPo(Subscribe.class);
		if (ss.getMail().length() > 0 || ss.getPhone().length() > 0) {
			if (subscribeDAO.saveSubscribe(ss)) {
				if (ss.getStype().equals("会员参与活动")) {
					form.addResult("jvalue", "参与活动成功！");
					try {
						UserinfoDAO userinfoDAO = new UserinfoDAO();
						List userinfoList = (List) userinfoDAO.findByAcount(ss
								.getUser());
						if (userinfoList.size() > 0) {
							Userinfo userinfo = (Userinfo) userinfoList.get(0);
							// 客户性别
							String sex = userinfo.getSex() ? "先生" : "女士";
							// 发送短信
							int sendSmsSucOrFail = SingletonClient
									.getClient()
									.sendSMS(
											new String[] { ss.getPhone() },
											"尊敬的"
													+ userinfo.getAcount()
													+ ""
													+ sex
													+ "，\r\n欢迎您参与wd本次活动，您的报名信息我们已经收到。",
											3);
							String YorN = (sendSmsSucOrFail == 0) ? "成功" : "失败";
							System.out.print("发送会员参与活动短信：  " + YorN);
						} else {
							// 发送短信
							int sendSmsSucOrFail = SingletonClient
									.getClient()
									.sendSMS(
											new String[] { ss.getPhone() },
											"尊敬的客户，\r\n欢迎您参与金客会本次活动，您的报名信息我们已经收到。",
											3);
							String YorN = (sendSmsSucOrFail == 0) ? "成功" : "失败";
							System.out.print("发送会员参与活动短信：  " + YorN);
						}

					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else if (ss.getStype().equals("非会员参与活动")) {
					form.addResult("jvalue", "参与活动成功！");
					try {
						// 发送短信
						int sendSmsSucOrFail = SingletonClient
								.getClient()
								.sendSMS(
										new String[] { ss.getPhone() },
										"尊敬的客户，\r\n欢迎您参与金客会的本次活动，您的报名信息我们已经收到，我们会尽快处理。",
										3);
						String YorN = (sendSmsSucOrFail == 0) ? "成功" : "失败";
						System.out.print("发送非会员参与活动短信：  " + YorN);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else if (ss.getStype().equals("关注商家优惠活动")) {
					form.addResult("jvalue", "关注商家优惠活动成功！");
				} else if (ss.getStype().equals("杂志订阅")) {
					form.addResult("jvalue", "订阅成功！");
				}
				// return doList(form, module);
			} else {
				form.addResult("jvalue", "订阅失败！");

				// return doList(form, module);
			}
		}
		return new Page("ajax", "ajaxResult.txt", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	public Page doAddActive(WebForm form, Module module) {
		Subscribe ss = (Subscribe) form.toPo(Subscribe.class);
		if (ss.getPhone().length() > 0) {
			if (subscribeDAO.saveSubscribe(ss)) {
				form.addResult("jvalue", "参与活动成功！");
				try {
					// 发送短信
					if (ss.getUser() == null) {
						int sendSmsSucOrFail = SingletonClient
								.getClient()
								.sendSMS(
										new String[] { ss.getPhone() },
										"尊敬的客户"
												+ ""
												+ "，\r\n欢迎您参与万达演艺本次活动，您的报名信息我们已经收到。",
										3);
						String YorN = (sendSmsSucOrFail == 0) ? "成功" : "失败";
						System.out.print("发送会员参与活动短信：  " + YorN);
						form.addResult("msg", YorN);
					} else {
						int sendSmsSucOrFail = SingletonClient
								.getClient()
								.sendSMS(
										new String[] { ss.getPhone() },
										"尊敬的"
												+ ss.getUser()
												+ ""
												+ "，\r\n欢迎您参与万达演艺本次活动，您的报名信息我们已经收到。",
										3);
						String YorN = (sendSmsSucOrFail == 0) ? "成功" : "失败";
						System.out.print("发送会员参与活动短信：  " + YorN);
						form.addResult("msg", YorN);
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {
				form.addResult("msg", "fali!!!");
			}
		}

		else {
			form.addResult("msg", "phone or email is wrong!!!");
		}

		return module.findPage("ajax");
		// return new Page("ajax", "ajaxResult.txt","html","/web/" +
		// thisSite.getTemplate() + "/");
	}

	public Page doSubscribeByPhone(WebForm form, Module module) {
		Subscribe ss = (Subscribe) form.toPo(Subscribe.class);
		String infoMsg = "";
		if (ss.getPhone().length() > 0) {
			if (subscribeDAO.saveSubscribe(ss)) {
				form.addResult("msg", "参与活动成功！");
				try {
					// 发送短信
					if (ss.getUser() == null) {
						int sendSmsSucOrFail = SingletonClient
								.getClient()
								.sendSMS(
										new String[] { ss.getPhone() },
										"尊敬的客户"
												+ ""
												+ "，\r\n欢迎您参与万达演艺本次活动，您的报名信息我们已经收到。",
										3);
						String YorN = (sendSmsSucOrFail == 0) ? "成功" : "失败";
						System.out.print("发送会员参与活动短信：  " + YorN);
						form.addResult("msg", YorN);
					} else {
						int sendSmsSucOrFail = SingletonClient
								.getClient()
								.sendSMS(
										new String[] { ss.getPhone() },
										"尊敬的"
												+ ss.getUser()
												+ ""
												+ "，\r\n欢迎您参与万达演艺本次活动，您的报名信息我们已经收到。",
										3);
						String YorN = (sendSmsSucOrFail == 0) ? "成功" : "失败";
						System.out.print("发送会员参与活动短信：  " + YorN);
						form.addResult("msg", YorN);
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {
				form.addResult("msg", "fali!!!");
			}

		} else {

			if (ss.getMail().length() > 0) {
				if (subscribeDAO.saveSubscribe(ss)) {
					form.addResult("msg", "参与活动成功！");

					String email = ss.getMail();
					InternetAddress[] address = null;
					try {
						ActionContext.getContext().getRequest()
								.setCharacterEncoding("utf8");
					} catch (Exception e) {
					}

					String mailserver = thisSite.getMailserver();// 发出邮箱的服务器
					String From = thisSite.getMailuser();// 发出的邮箱
					String to = email;// 发到的邮箱
					String Subject = "[" + "尊敬的客户" + "]您好";// 标题
					String type = "text/plain";// 发送邮件格式为html
					String messageText = "\r\n欢迎您参与万达演艺的本次活动，您的报名信息我们已经收到，我们会尽快处理。";// 发送内容
					boolean sessionDebug = false;
					try {
						// 设定所要用的Mail 服务器和所使用的传输协议
						java.util.Properties props = System.getProperties();
						props.put("mail.host", mailserver);
						props.put("mail.transport.protocol", "smtp");
						props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证
						// 指明环境编码，否则在Linux环境下有可能乱码
						System.setProperty("mail.mime.charset", "UTF-8");
						// 产生新的Session 服务
						javax.mail.Session mailSession = javax.mail.Session
								.getDefaultInstance(props, null);
						mailSession.setDebug(sessionDebug);
						Message msg = new MimeMessage(mailSession);
						// 设定发邮件的人
						msg.setFrom(new InternetAddress(From));
						// 设定收信人的信箱
						address = InternetAddress.parse(to, false);
						msg.setRecipients(Message.RecipientType.TO, address);
						// 设定信中的主题
						msg.setSubject(Subject);
						// 设定送信的时间
						msg.setSentDate(new Date());
						Multipart mp = new MimeMultipart();
						MimeBodyPart mbp = new MimeBodyPart();
						// 设定邮件内容的类型为 text/plain 或 text/html
						mbp.setContent(messageText, type + ";charset=UTF-8");
						mp.addBodyPart(mbp);
						msg.setContent(mp);
						Transport transport = mailSession.getTransport("smtp");
						transport.connect(mailserver, thisSite.getMailuser(),
								thisSite.getMailpass());// 设发出邮箱的用户名、密码
						transport.sendMessage(msg, msg.getAllRecipients());
						transport.close();
						// Transport.send(msg);
						// infoMsg = "邮件已顺利发送！";
						form.addResult("msg", "邮件已顺利发送！");
						// out.println("邮件已顺利发送！");
							
					} catch (Exception mex) {
						mex.printStackTrace();
						infoMsg = "发送失败：" + mex;
						// form.addResult("msg", "发送失败：" + mex);
					}
				} else {
					infoMsg = "邮箱错误！";
					// form.addResult("msg", "邮箱错误！");
				}

			} else {
				form.addResult("msg", "phone or email is wrong!!!");
			}
			
		}
		form.addResult("msg", infoMsg);
		return module.findPage("ajax");
		// return new Page("ajax", "ajaxResult.txt","html","/web/" +
		// thisSite.getTemplate() + "/");
	}



	public Page doDelete(WebForm form, Module module) {
		String mail = CommUtil.null2String(form.get("mail"));
		Subscribe ss = subscribeDAO.getSubscribeByMail(mail);
		// System.out.println("返回的订阅ID:"+ss.getId());
		if (subscribeDAO.delSubscribe(ss)) {
			form.addResult("jvalue", "取消成功！");
			// return doList(form, module);
		} else {
			form.addResult("jvalue", "取消失败！");
			// return doList(form, module);
		}
		return new Page("ajax", "ajaxResult.txt", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}
}
